<?php
/*
 * Created  : Mon 16 Nov 2009 07:48:57 PM EST
 * Modified : Sun 03 Jan 2010 12:25:37 PM EST
 *
 * Copyright 2009 Gautam Iyer <gi1242@nospam.com> (Replace nospam with gmail).
 *
 * This file is part of phpss.
 *
 * phpss is free software: you can redistribute it and/or modify it under the 
 * terms of the GNU General Public License as published by the Free Software 
 * Foundation, either version 3 of the License, or (at your option) any later 
 * version.
 *
 * phpss is distributed in the hope that it will be useful, but WITHOUT ANY 
 * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS 
 * FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more 
 * details.
 *
 * You should have received a copy of the GNU General Public License along with 
 * phpss.  If not, see <http://www.gnu.org/licenses/>.
 *
 */

/*
 * If src recursively into dst. dst should be directory (regardless of whether 
 * src is a file or not).
 */
function rcopy( $src, $dst )
{
  if( mkdir_if_needed( $dst ) )
    die( "Could not create $dst\n" );

  $basename_src = basename( $src );
  try
  {
    if( is_file( $src ) )
    {
      if( !@copy( $src, "$dst/$basename_src" ) )
       	throw new Exception( "Error copying $src" );
    }
    elseif( is_dir( $src ) )
    {
      foreach( scandir( $src ) as $f )
      {
	if( $f != "." && $f != ".." )
	  rcopy( "$src/$f", "$dst/$basename_src" );
      }
    }
    else throw new Exception( "$src is not a file or directory" );
  }
  catch( Exception $e )
  {
      fwrite( STDERR, ER . $e->getMessage() . RE . "\n" );
  }
}

/*
 * Copy contents of src into dst (i.e. cp src/* dst )
 */
function copy_contents( $src, $dst )
{
  fwrite( STDERR, "Copying contents of $src into $dst.\n" );

  if( is_file( $src ) )
    rcopy( $src, $dst );
  elseif( is_dir( $src ) )
  {
    foreach( scandir( $src ) as $f )
    {
      if( $f != '.' && $f != ".." && $f != ".svn" )
	rcopy( "$src/$f", "$dst" );
    }
  }
}

/*
 * mkdir (if it doesn't exist). Supports sshfs based mounts.
 */
function mkdir_if_needed( $dst )
{
  return !is_dir( $dst ) && !mkdir( $dst, 0777, true );
}
?>
